package com.lzw.breadknife.skin;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * todo: 高版本的系统中暂时未做测试，不清楚该工具类可行不？以后有空的话，建议使用云真机平台获取一下不同型号手机权限设置页面的Activity名称。
 */
class GetPermissionUtil {

    public static final String TAG = GetPermissionUtil.class.getSimpleName();

    /**
     * 手动跳转到手机的权限设置页面，这里适配了常见的不同国产品牌手机类型
     * @param context
     */
    public static void gotoPermission(Context context) {
        String manufacturer = Build.MANUFACTURER; // 手机制造商，网上有些人使用这个来获取，经测试它和Build.BRAND是一致的(如有疑问欢迎提issues)。
        String brand = Build.BRAND; // 品牌名
        if (TextUtils.equals(manufacturer.toLowerCase(), "redmi") || TextUtils.equals(manufacturer.toLowerCase(), "xiaomi")) {
            gotoMiuiPermission(context); // 小米
        } else if (TextUtils.equals(manufacturer.toLowerCase(), "huawei") || TextUtils.equals(manufacturer.toLowerCase(), "honor")) {
            gotoHuaweiPermission(context); // 华为
        } else if (TextUtils.equals(manufacturer.toLowerCase(), "oppo")) {
            gotoOPPOPermission(context); // OPPO
        } else if (TextUtils.equals(manufacturer.toLowerCase(), "vivo")) {
            gotoVIVOPermission(context); // VIVO
        } else if (TextUtils.equals(manufacturer.toLowerCase(), "meizu")) {
            gotoMeizuPermission(context); // 魅族
        } else {
            context.startActivity(getAppDetailSettingIntent(context));
        }
    }

    /**
     * 跳转到miui的权限管理页面
     */
    private static void gotoMiuiPermission(Context context) {
//        try { // MIUI 8
//            Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
//            localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
//            localIntent.putExtra("extra_pkgname", context.getPackageName());
//            context.startActivity(localIntent);
//        } catch (Exception e) {
//            try { // MIUI 5/6/7
//                Intent localIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
//                localIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
//                localIntent.putExtra("extra_pkgname", context.getPackageName());
//                context.startActivity(localIntent);
//            } catch (Exception e1) { // 不然跳转到应用详情
//                context.startActivity(getAppDetailSettingIntent(context));
//            }
//        }

        // 为了带阿米健壮性，动态获取MIUI版本号比较好：
        try {
            String rom = getMiuiVersion();
            Log.d(TAG,"getMiuiVersion:" + rom);
            Intent intent = new Intent();
            if ("V6".equals(rom) || "V7".equals(rom)) {
                intent.setAction("miui.intent.action.APP_PERM_EDITOR");
                intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
                intent.putExtra("extra_pkgname", context.getPackageName());
            } else if ("V8".equals(rom) || "V9".equals(rom)) {
                intent.setAction("miui.intent.action.APP_PERM_EDITOR");
                intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
                intent.putExtra("extra_pkgname", context.getPackageName());
            } else if ("V130".equals(rom)){
                intent= new Intent("miui.intent.action.APP_PERM_EDITOR");
                intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
                intent.putExtra("extra_pkgname", context.getPackageName());
            }
        } catch (Exception e){
            e.printStackTrace();
            // 如果都找不到的话，跳转到应用详情
            context.startActivity(getAppDetailSettingIntent(context));
        }
    }

    private static String getMiuiVersion() {
        String propName = "ro.miui.ui.version.name";
        String line = null;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + propName);
            input = new BufferedReader(
                    new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return line;
    }



    /**
     * 华为的权限管理页面
     */
    private static void gotoHuaweiPermission(Context context) {
        try {
            String brand = Build.BRAND;
            if(brand.toLowerCase().equals("p20") || brand.toLowerCase().equals("p30")) { // 适配华为P20和P30
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");
                intent.setComponent(comp);
                context.startActivity(intent);
            } else { // 华为P20之前的手机型号
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity");
                intent.setComponent(comp);
                context.startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
            context.startActivity(getAppDetailSettingIntent(context));
        }
    }

    /**
     * 跳转到OPPO的权限管理系统
     */
    private static void gotoOPPOPermission(Context context) {
        try {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("packageName", context.getPackageName());
            //        ComponentName comp = new ComponentName("com.color.safecenter", "com.color.safecenter.permission.PermissionManagerActivity");
            ComponentName comp = new ComponentName("com.coloros.securitypermission", "com.coloros.securitypermission.permission.PermissionAppAllPermissionActivity");//R11t 7.1.1 os-v3.2
            intent.setComponent(comp);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            getAppDetailSettingIntent(context);
        }
    }

    /**
     * 跳转到VIVO的权限管理系统
     */
    private static void gotoVIVOPermission(Context context) {
        try {
            Intent intent = new Intent("android.intent.action.MAIN");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("packageName", context.getPackageName());
            ComponentName comp = new ComponentName("com.android.settings", "com.vivo.permissionmanager.activity.PurviewTabActivity");
            intent.setComponent(comp);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            getAppDetailSettingIntent(context);
        }

    }

    /**
     * 跳转到魅族的权限管理系统
     */
    private static void gotoMeizuPermission(Context context) {
        try {
            Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.putExtra("packageName", context.getPackageName());
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            context.startActivity(getAppDetailSettingIntent(context));
        }
    }

    /**
     * 获取应用详情页面intent（若是找不到要跳转的界面，也能够先把用户引导到系统设置页面）
     */
    private static Intent getAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));

        return localIntent;
    }

}
